package com.lx.spring.jdbc.dao;


import com.lx.spring.jdbc.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AccountDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<Account> query(){
        String sql = "select * from bank_account";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
    }

    public Account queryById(Long id){
        String sql = "select * from bank_account where id=?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class), id);
    }

    public void insert(long id, String pwd, double balance){
        String sql = "insert into bank_account values(?,?,?)";
        jdbcTemplate.update(sql, id, pwd, balance);
    }

    public int updateBalanceById(long id, double money){
        String sql = "update bank_account set balance= balance + ? where id=?";
        return jdbcTemplate.update(sql, money, id);
    }

    public Account login(long id, String pwd){
        String sql = "select * from bank_account where id=? and password=?";
        // new BeanPropertyRowMapper<Account>(Account.class) 查询返回类型
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class), id, pwd);
    }
    public double queryBalanceById(long id){
        String sql = "select balance from bank_account where id=?";
        return jdbcTemplate.queryForObject(sql, Double.class, id);
    }
}
